package com.jalarbee.core.bootik.bon.dao.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.jalarbee.core.bootik.bon.business.Bon;
import com.jalarbee.core.bootik.bon.dao.BonDao;
import com.jalarbee.core.bootik.client.business.Client;
import com.jalarbee.core.generic.dao.impl.GenericDaoJpa;
import com.jalarbee.core.util.Chunk;

@Repository(value="bonDao")
public class BonDaoJpa extends GenericDaoJpa<Bon, Integer> implements BonDao {

	@SuppressWarnings("unchecked")
	@Override
	public List<Bon> getBons(Client client, Date from, Date to, Chunk chunk) {
		StringBuffer buffer = new StringBuffer();
		buffer.append("from Bon b where true=true");
		if(client != null) {
			buffer.append(" and b.client = :client");
		}
		if(from != null) {
			buffer.append(" and b.openFromDate >= :from");
		}
		if(to != null) {
			buffer.append(" and b.openFromDate <= :to");
		}
		Query query = getEntityManager().createQuery(buffer.toString());
		if(client != null) {
			query.setParameter("client", client);
		}
		if(from != null) {
			query.setParameter("from", from);
		}
		if(to != null) {
			query.setParameter("to", to);
		}
		if(chunk != null && chunk.makesSense()) {
			query = query.setFirstResult(chunk.getStart());
			query = query.setMaxResults(chunk.getSize());
		}
		return query.getResultList();
	}
}
